'''
Created on 20.11.2009

@author: guest
'''
import cgi
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from ru.simpleprojecttool.db.model import Task, Project, Participant, Comment
from ru.simpleprojecttool.utils import utils
from django.utils import simplejson

class ListTasks(webapp.RequestHandler):
    project = Project
    current = 0
    pageSize = 20
    def execute(self):
        tasks = Task.all().filter('project = ', self.project)
        my = False
        assignedToMe = False
        canEditProject = False
        status = str()
        
        if self.request.get('status'):
            tasks.filter('status = ', self.request.get('status'))
            status = self.request.get('status')

        if self.request.get('createdByMe') == 'on':
            tasks = tasks.filter('creator = ', users.get_current_user())
            my = True

        if self.request.get('assignedToMe') == 'on':
            tasks = tasks.filter('assignedTo = ', utils.getParticipantByUser(self.project))
            assignedToMe = True

        if utils.canEditProject(self.project):
            canEditProject = True
           
        if self.request.get('current'):
            self.current = int(self.request.get('current')) ;
            
        if self.current < 0:
            self.current = 0
            
        if self.request.get('pageSize'):
            self.pageSize = int(self.request.get('pageSize'))
        
        isLastPage = False 
        tasks.order('-createdAt') 
        count = tasks.count()
        
        tasks = tasks.fetch(int(self.pageSize), int(self.current))
        
        
        
        if len(tasks) < self.pageSize:
            isLastPage = True
        
        isFirstPage = False
        if self.current == 0:
            isFirstPage = True
        
        template_values = {
                   'project': self.project, 
                   'tasks': tasks , 
                   'canEditProject': canEditProject, 
                   'isLastPage':  isLastPage,
                   'isFirstPage': isFirstPage, 
                   'current': self.current, 
                   'pageSize': self.pageSize, 
                   'count': count
                   }
        
        if status:
            template_values['status'] = status
        template_values['my'] = my
        template_values['assignedToMe'] = assignedToMe
            
        utils.showTemplate(self, '../../../templates/task/tasks.html', [], template_values)
    
    def get(self):
        self.project = db.get(db.Key(self.request.get('projectId')))
        utils.checkParticipant(self.project, self)

class CreateTask(webapp.RequestHandler):
    project = Project
    def execute(self):
        participants = Participant.all().filter("project = ", self.project)
        aParticipans = []
        no = 1
        
        
        nos = Task.all().filter('project = ', self.project).order('-index').fetch(1)
        if len(nos) > 0:
            no = nos[0].index + 1
            
        
        for participant in participants:
            if utils.participantCanBeAssigned(participant):
                aParticipans.append(participant)
        
        template_values = {
                   'projectId': self.request.get('projectId'),
                   'participants' : aParticipans,
                   'no': no 
                   }
        utils.showTemplate(self, '../../../templates/task/createTask.html', [], template_values)

    def get(self):
        self.project = db.get(db.Key(self.request.get('projectId')))
        utils.checkCanAssign(self.project, self)

class CreateTaskAction(webapp.RequestHandler):
    project = Project
    def execute(self):
        userToAssign = users.User(self.request.get('assignedTo'))
        participant = Participant.all().filter("project = ", self.project).filter("user = ", userToAssign)[0]
        
        task = Task(name = self.request.get('taskName'),
                    description = self.request.get('description') , 
                    priority = int(self.request.get('priority')), 
                    project = self.project, 
                    index = int(self.request.get('no')), 
                    creator = users.get_current_user(), 
                    assignedTo = participant, 
                    status = 'CREATED')
        task.put()
        self.redirect('/tasks?projectId=%s' % (self.request.get('projectId')))
    def post(self):
        self.project = db.get(db.Key(self.request.get('projectId')))
        utils.checkCanAssign(self.project, self)
        
        
class EditTask(webapp.RequestHandler):
    task = Task
    def execute(self):
        isAssignedToMe = False 
        isCreator = False
        currentUser = users.get_current_user()
        if self.task.assignedTo.user == currentUser:
            isAssignedToMe = True
        
        if self.task.creator == currentUser:
            isCreator = True

        participants = Participant.all().filter("project = ", self.task.project)
        aParticipans = []
        for participant in participants:
            if utils.participantCanBeAssigned(participant):
                aParticipans.append(participant)

        comments = Comment.all().filter('task = ', self.task).fetch(100, 0)
        
        for comment in comments:
            comment.text = comment.text.replace('\n', '<br />')
        
        canEdit = isCreator and self.task.status == 'CREATED'
        
        template_values = {
                           'task': self.task, 
                           'assignedToMe': isAssignedToMe, 
                           'createdByMe': isCreator, 
                           'participants': aParticipans, 
                           'comments': comments, 
                           'canEdit': canEdit
                           }
        utils.showTemplate(self, '../../../templates/task/editTask.html', [], template_values)
    def get(self):
        self.task = db.get(db.Key(self.request.get('taskId')))
        utils.checkCanEditTask(self.task, self)
        
class SaveTask(webapp.RequestHandler):
    task = Task
    
    def execute(self):
        if self.request.get('no'):
            self.task.index = int(self.request.get('no'))
        if self.request.get('taskName'):
            self.task.name = self.request.get('taskName')
        if self.request.get('description'):
            self.task.description = self.request.get('description')
        if self.request.get('status'):
            self.task.status = self.request.get('status')
        if self.request.get('assignedTo'):
            userToAssign = users.User(self.request.get('assignedTo'))
            participant = Participant.all().filter("project = ", self.task.project).filter("user = ", userToAssign)[0]
            self.task.assignedTo = participant
        if self.request.get('priority'):
            self.task.priority = int(self.request.get('priority'))
        
        self.task.put()
        self.redirect('/tasks?projectId=%s' % str(self.task.project.key()))
    def post(self):
        self.task = db.get(db.Key(self.request.get('taskId')))
        utils.checkCanEditTask(self.task, self)

class DeleteTask(webapp.RequestHandler):
    task = Task
    def execute(self):
        project = self.task.project
        db.delete(self.task)
        self.redirect('/tasks?projectId=%s' % str(project.key()))
    def post(self):
        self.task = db.get(db.Key(self.request.get('taskId')))
        utils.checkDeleteTask(self.task, self)
        
class TasksCount(webapp.RequestHandler):
    project = Project
    def execute(self):
        count = Task.all().filter("project = ", self.project).count() ;
        self.response.headers["Content-Type"] = 'text/plain' 
        self.response.out.write('{ \'count\': \'%d\' }' % count)
    def get(self):
        self.project = db.get(db.Key(self.request.get('projectId')))
        self.execute()


class TasksJSON(webapp.RequestHandler) :
    def get(self):
        project = db.get(db.Key(self.request.get('projectId')))
        tasks = Task.all().filter('project = ', project)

        jsonTasks = []

        for task in tasks:
            jsonTask = {
                'id': task.key().__str__(),
                'index': task.index,
                'name': task.name,
                'createdAt': task.createdAt.strftime('%d.%m.%Y %H:%M'),
                'createdBy': task.creator.nickname(),
                'assignedTo': task.assignedTo.user.nickname(),
                'priority': task.priority,
                'status': task.status
            }

            jsonTasks.append(jsonTask)

        jsonData = {
            'projectId': project.key().__str__(), 
            'tasks': jsonTasks
        }

        self.response.out.write(simplejson.dumps(jsonData))

class CreateTaskJSON(webapp.RequestHandler):
    def post(self) :
        project = db.get(db.Key(self.request.get('projectId')))
        try :
            userToAssign = users.User(self.request.get('assignedTo'))
            participant = Participant.all().filter("project = ", project).filter("user = ", userToAssign)[0]
            no = 1


            nos = Task.all().filter('project = ', project).order('-index').fetch(1)
            if len(nos) > 0:
                no = nos[0].index + 1

            task = Task(name = self.request.get('name'),
                        description = self.request.get('description') ,
                        priority = int(self.request.get('priority')),
                        project = project,
                        index = no,
                        creator = users.get_current_user(),
                        assignedTo = participant,
                        status = 'CREATED')
            task.put()

            jsonData = {
                'success': 1,
                'id': task.key().__str__(),
                'index': task.index,
                'name': task.name,
                'createdAt': task.createdAt.strftime('%d.%m.%Y %H:%M'),
                'createdBy': task.creator.nickname(),
                'assignedTo': task.assignedTo.user.nickname(),
                'priority': task.priority,
                'status': task.status,
                'projectId': task.project.key().__str__()
            }
            self.response.out.write(simplejson.dumps(jsonData))

        except :
            jsonData = {
                'success': 0, 
            }
            self.response.out.write(simplejson.dumps(jsonData))




